package com.revzone.demo001.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.revzone.demo001.entity.*;
import com.revzone.demo001.mapper.QrcodeMapper;
import com.revzone.demo001.mapper.UserMapper_old;
import com.revzone.demo001.service.QrcodeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;


import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

@RestController // 添加此注解
@RequestMapping("/qrcode") // 添加基础路径

public class QrcodeController {

    @Autowired
    QrcodeMapper qrcodeMapper;
    @Autowired
    QrcodeService qrcodeService;
//    @Value("${revzone.PIC_ADDRESS}")
    private String PIC_ADDRESS = "D:/revzone/Otoc/Address";
    @Autowired
    private ApplicationArguments applicationArguments;
    @Autowired
    private UserMapper_old userMapper;

    @PostMapping(value="/list", produces = "application/json;charset=UTF-8")
//    @ApiOperation(value = "查询所有资源！")
    public Result listResources(@RequestBody(required = false) Qrcode qrcode ) {
        QueryWrapper<Qrcode> wrapper = new QueryWrapper<>();
        if (qrcode != null) {
            if (qrcode.getId() != null) wrapper.eq("id",qrcode.getId());
            if (qrcode.getName() != null) wrapper.eq("name",qrcode.getName());
            if (qrcode.getType() != null) wrapper.eq("type",qrcode.getType());
        }
        return Result.success(qrcodeMapper.selectList(wrapper));
    }

    @PostMapping(value="/page", produces = "application/json;charset=UTF-8")
//    @ApiOperation(value = "查询所有资源！")
    public Result pageResources(@RequestBody(required = false) PageResultMap<Qrcode> pageResultMap ) {
        Qrcode qrcode = new Qrcode();
        Page<Qrcode> taskPage;
        QueryWrapper<Qrcode> wrapper = new QueryWrapper<>();
        if (pageResultMap != null) {
            if (pageResultMap.map != null) {
                BeanUtils.copyProperties(pageResultMap.map,qrcode);
//                wrapper = BaseEntity.getQueryWrapper(task);
                if (qrcode.getId() != null) wrapper.eq("id",qrcode.getId());
                if (qrcode.getName() != null) wrapper.eq("name",qrcode.getName());
                if (qrcode.getType() != null) wrapper.eq("type",qrcode.getType());
            }
        } else pageResultMap = new PageResultMap<>();
        try {
            Page<Qrcode> page = new Page<>(pageResultMap.getCurrentPage(),pageResultMap.getPageSize());
            wrapper.orderByAsc("id");
            taskPage = qrcodeService.page(page, wrapper);
        } catch (BeansException e) {
            throw new RuntimeException(e);
        }
        // 将查询结果封装到 PageResult 类型的对象中
        PageResult<Qrcode> result = new PageResult<Qrcode>(taskPage);
        return Result.success(result);
    }


    @GetMapping(value="/getFile", produces = "application/json;charset=UTF-8")
//    @ApiOperation(value = "查询对应图片！")
    public ResponseEntity<?> getFile(@RequestParam(required = false) Integer id ) throws IOException {
        // 从数据库获取 mapAddress
        Qrcode picaddress = qrcodeMapper.selectById(id);
        String mapAddress = picaddress.getUrl();

        // 假设 mapAddress 是存储图片的绝对路径
        File file = new File(mapAddress);

        if (file.exists() && file.isFile()) {
            // 使用 FileInputStream 来读取文件
            FileInputStream fileInputStream = new FileInputStream(file);
            long fileLength = file.length();

            // 使用 Files.probeContentType() 来自动获取文件的 MIME 类型
            Path filePath = file.toPath();
            String mimeType = Files.probeContentType(filePath);

            // 设置响应头
            HttpHeaders headers = new HttpHeaders();
            headers.add(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=" + file.getName());  // 以图片方式返回
            headers.add(HttpHeaders.CONTENT_LENGTH, String.valueOf(fileLength));  // 文件大小

            // 如果 MIME 类型为空，设置默认的图片类型
            if (mimeType == null) {
                mimeType = "application/octet-stream";  // 默认返回二进制流
            }

            // 返回图片内容，使用 InputStreamResource
            InputStreamResource resource = new InputStreamResource(fileInputStream);
            return ResponseEntity.ok()
                    .headers(headers)
                    .contentType(MediaType.parseMediaType(mimeType))  // 设置动态获取的 MIME 类型
                    .body(resource);  // 返回 InputStreamResource 作为响应体
        } else {
            // 文件不存在，返回 404
            return ResponseEntity.notFound().build();
        }

    }

    @PostMapping(value="/add", produces = "application/json;charset=UTF-8")
//    @ApiOperation(value = "新增资源！")
//    @RequiresRoles(logical = Logical.OR, value = {"root","user", "admin"})
    @Transactional  // 加上 @Transactional 注解，确保事务管理
    public Result addResource(@RequestBody(required = false) Qrcode qrcode) {

        return Result.success(qrcodeService.save(qrcode));
    }

    @PostMapping(value="/update", produces = "application/json;charset=UTF-8")
//    @ApiOperation(value = "更新资源！")
    public Result updateResource(@RequestBody(required = false) Qrcode qrcode) {
        return Result.success(qrcodeMapper.updateById(qrcode));
    }

    @GetMapping(value="/delete", produces = "application/json;charset=UTF-8")
//    @ApiOperation(value = "删除资源！")
    public Result deleteResource(@RequestParam(required = false) Long id) {
        return Result.success(qrcodeMapper.deleteById(id));
    }

    @PostMapping(value="/GenerateQrcode", produces = "application/json;charset=UTF-8")
    public Result GenerateQrcode(@RequestParam(required = false) Integer count,
                                 @RequestParam(required = false) Integer productType,
                                 @RequestParam(required = false) String urlPrefix,
                                 @RequestParam(required = false) String remarks) {
        return Result.success(qrcodeService.generateUniqueCodes(productType, count, urlPrefix, remarks));
    }
    //导出TXT
    @PostMapping(value="/ExportQrcode", produces = "application/json;charset=UTF-8")
    public Result ExportQrcode(@RequestParam(required = false) String startcount, @RequestParam(required = false) String endcount, @RequestParam(required = false) String exportDir) {
        return Result.success(qrcodeService.ExportQrcode(startcount, endcount, exportDir));

    }


}
